import { CloseCircleOutlined } from '@ant-design/icons';
import {
  FooterToolbar,
  PageContainer,
  ProForm,
  ProFormSelect,
  ProFormText,
  ProFormTextArea
} from '@ant-design/pro-components';
import { Button, Card, Col, Form, message, Popover, Row } from 'antd';
import type { FC } from 'react';
import { useState } from 'react';
import { getApiCase, saveUiCasePage, updateUiCasePage } from './service';
import useStyles from './style.style';
import { pageModule } from '../../api-case-module/service';
import CustomDragTable from './components/CustomDragTable';
import { history, useModel, useRequest, useSearchParams } from '@umijs/max';
import { setKey } from '@/utils';

type InternalNamePath = (string | number)[];

interface ErrorField {
  name: InternalNamePath;
  errors: string[];
}
const AdvancedForm: FC<Record<string, any>> = () => {
  const { styles } = useStyles();
  const [searchParams, setSearchParams] = useSearchParams()
  const id = searchParams.get('id')
  const [form] = Form.useForm()
  const [error, setError] = useState<ErrorField[]>([]);
  const { initialState } = useModel('@@initialState');

  const getErrorInfo = (errors: ErrorField[]) => {
    const errorCount = errors.filter((item) => item.errors.length > 0).length;
    if (!errors || errorCount === 0) {
      return null;
    }
    const scrollToField = (fieldKey: string) => {
      const labelNode = document.querySelector(`label[for="${fieldKey}"]`);
      if (labelNode) {
        labelNode.scrollIntoView(true);
      }
    };
    const errorList = errors.map((err) => {
      if (!err || err.errors.length === 0) {
        return null;
      }
      const key = err.name[0] as 'name' | 'url' | 'owner' | 'approver' | 'dateRange' | 'type';
      return (
        <li key={key} className={styles.errorListItem} onClick={() => scrollToField(key)}>
          <CloseCircleOutlined className={styles.errorIcon} />
          {/* <div className={styles.errorMessage}>{err.errors[0]}</div>
          <div className={styles.errorField}>{fieldLabels[key]}</div> */}
        </li>
      );
    });
    return (
      <span className={styles.errorIcon}>
        <Popover
          title="表单校验信息"
          content={errorList}
          overlayClassName={styles.errorPopover}
          trigger="click"
          getPopupContainer={(trigger: HTMLElement) => {
            if (trigger && trigger.parentNode) {
              return trigger.parentNode as HTMLElement;
            }
            return trigger;
          }}
        >
          <CloseCircleOutlined />
        </Popover>
        {errorCount}
      </span>
    );
  };

  const onFinish = async (values: Record<string, any>) => {
    const hide = message.loading('正在保存');

    try {
      const api = id ? updateUiCasePage : saveUiCasePage

      const res = await api({
        ...values,
        id: id,
        projectId: initialState?.currentProject?.id,
        steps: values?.steps?.map((item: any, index: number) => {
          let body = ''
          if (item?.bodyType != 'NONE') {
            body = JSON.stringify(item?.[item?.bodyType])
          }

          return {
            ...item,
            projectId: initialState?.currentProject?.id,
            header: JSON.stringify(item?.header),
            body,
            query: JSON.stringify(item?.query),
            relation: JSON.stringify(item?.relation),
            assertion: JSON.stringify(item?.assertion),
            num: index
          }
        }),

      });
      hide();
      if (res?.code == 0) {
        message.success('保存成功');
        if (res?.data?.id) {
          setSearchParams({
            id: res?.data?.id
          })
        }
        refresh()
        return true;
      } else {
        message.error('保存失败请重试！');
        return false;
      }
    } catch (error) {
      hide();
      message.error('保存失败请重试！');
      return false;
    }
  };

  const onFinishFailed = (errorInfo: any) => {
    setError(errorInfo.errorFields);
  };

  const { data, refresh } = useRequest(() => {
    return getApiCase({ id, projectId: initialState?.currentProject?.id })
  }, {
    refreshDeps: [id], ready: !!id, onSuccess(data) {
      form.setFieldsValue({
        ...data,
        steps: data?.steps?.map((item: any) => {

          const newItem = {
            ...item,
            key: item?.id
          }

          try {
            if (newItem.header) {
              newItem.header = setKey(JSON.parse(newItem.header), 'id')
            }
            if (newItem.body) {
              const body = JSON.parse(newItem.body)
              newItem[newItem.bodyType] = setKey(body, 'id')
            }
            if (newItem.query) {
              newItem.query = setKey(JSON.parse(newItem.query), 'id')
            }
            if (newItem.relation) {
              newItem.relation = setKey(JSON.parse(newItem.relation))
            }
            if (newItem.assertion) {
              newItem.assertion = setKey(JSON.parse(newItem.assertion))
            }

          } catch (e) { }
          return newItem
        })
      })
    }
  })

  return (
    <ProForm
      layout="vertical"
      requiredMark
      submitter={{
        render: (props, dom) => {
          return (
            <FooterToolbar>
              {getErrorInfo(error)}
              <Button onClick={() => {
                history.push('/api-auto/case')
              }}>返回</Button>
              {dom}
            </FooterToolbar>
          );
        },
      }}
      form={form}
      initialValues={{
        steps: [],
        level: 'p3',
        browser: 'CHROME'
      }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
    >
      <PageContainer>
        <Card title="用例信息" className={styles.card} bordered={false}>
          <Row gutter={16}>
            <Col lg={6} md={12} sm={24}>
              <ProFormText
                label={'接口用例名称'}
                name="name"
                rules={[
                  {
                    required: true,
                    message: '请输入接口用例名称',
                  },
                ]}
                placeholder="请输入接口用例名称"
              />
            </Col>
            <Col lg={6} md={12} sm={24}>
              <ProFormSelect
                label={'接口用例所属模块'}
                name="moduleId"
                rules={[
                  {
                    required: true,
                    message: '请选择接口用例所属模块',
                  },
                ]}

                request={async () => {
                  const res = await pageModule({ current: 1, pageSize: 100 })

                  return res?.data?.currentData?.map((item: any) => ({
                    label: item?.name,
                    value: item?.id,
                  })) || []
                }}
                placeholder="请选择接口用例所属模块"
              />
            </Col>

            <Col lg={6} md={12} sm={24}>
              <ProFormSelect
                label={'接口等级'}
                name="level"
                rules={[
                  {
                    required: true,
                    message: '请选择接口等级',
                  },
                ]}
                options={[
                  {
                    label: 'P0',
                    value: 'p0',
                  },
                  {
                    label: 'P1',
                    value: 'p1',
                  },
                  {
                    label: 'P2',
                    value: 'p2',
                  },
                  {
                    label: 'P3',
                    value: 'p3',
                  },
                ]}
                placeholder="请选择接口等级"
              />
            </Col>
            <Col lg={24} md={24} sm={24}
            >
              <ProFormTextArea
                label={'接口用例描述'}
                name="description"
                fieldProps={{ maxLength: 200 }}
                placeholder="请输入接口用例描述"
              />
            </Col>
          </Row>
        </Card>
        <Card title="步骤列表" bordered={false}>
          <ProForm.Item name="steps">
            <CustomDragTable form={form} data={data} />
          </ProForm.Item>
        </Card>
      </PageContainer>
    </ProForm>
  );
};
export default AdvancedForm;
